import java.util.PriorityQueue;

class MyTask implements Comparable<MyTask>{//任务runnable + 时间delay
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
    public long getTime(){
        return this.time;
    }
    public Runnable getRunnable(){
        return this.runnable;
    }
}
class MyTimer1{//计时器
    private PriorityQueue<MyTask> priorityQueue = new PriorityQueue<>();
    Object locker = new Object();
    public MyTimer1(){
        Thread t = new Thread(() -> {
            while(true){
                try{
                    synchronized (locker){
                        while(priorityQueue.isEmpty()){
                            locker.wait();
                        }
                        MyTask myTask = priorityQueue.peek();
                        long curTime = System.currentTimeMillis();
                        if(curTime >= myTask.getTime()){
                            myTask.getRunnable().run();
                            priorityQueue.poll();
                        }else {
                            locker.wait(myTask.getTime() - curTime);
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable, long delay){
        synchronized (locker){
            priorityQueue.offer(new MyTask(runnable,delay));
            locker.notify();
        }
    }
}
public class Demo3 {
    public static void main(String[] args) {
        MyTimer1 myTimer1 = new MyTimer1();
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("aaa");
            }
        },1000);
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("aab");
            }
        },2000);
    }
}
